class MyPromise {
    constructor(callback) {
        // 初始化状态
        this.status = 'pending'
        // 初始化成功状态的值
        this.value = undefined
        // 初始化失败状态的值
        this.reason = undefined
        // 储存成功状态的回调函数
        this.onResolvedCallbacks = []
        // 储存失败状态的回调函数
        this.onRejectedCallbacks = []

        // 定义resolve函数
        const resolve = value => {
            if (this.status == 'pending') {
                this.status = 'resolved'
                this.value = value
                this.onResolvedCallbacks.forEach(cb => cb())
            }
        }

        const reject = reason => {
            if (this.status == 'pending') {
                this.status = 'rejected'
                this.reason = reason
                this.onRejectedCallbacks.forEach(cb => cb())
            }
        }

        callback(resolve, reject)
    }

    then (onResolved, onRejected) {
        const newPromise = new MyPromise((resolve, reject) => {
            if (this.status === 'resolved') {
                try {
                    const x = onResolved(this.value)
                    resolve(x)
                } catch (error) {
                    reject(error)
                }
            }

            if (this.status === 'rejected') {
                try {
                    const x = onRejected(this.reason)
                    resolve(x)
                } catch (error) {
                    reject(error)
                }
            }

            if (this.status === 'pending') {
                this.onResolvedCallbacks.push(() => {
                    try {
                        const x = onResolved(this.value)
                        resolve(x)
                    } catch (error) {
                        reject(error)
                    }
                })
                this.onRejectedCallbacks.push(() => {
                    try {
                        const x = onRejected(this.reason)
                        resolve(x)
                    } catch (error) {
                        reject(error)
                    }
                })
            }
        })
        return newPromise
    }

    catch (onRejected) {
        return this.then(null, onRejected)
    }
}

// new Promise(function (resolve, reject) { })

const m = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        console.log(1)
        resolve('成功')
    }, 1000)
})

m.then(val => {
    console.log(2)
    return 11
}).then(val => {
    console.log(3)
    return new MyPromise((resolve, reject) => {
        setTimeout(() => {
            resolve('成功2')
        }, 1000)
    })
}).then(val => {
    console.log(val)
    throw new Error('error')
}).catch(err => {
    console.log(err)
})
// console.log(m)